package com.example.stars_project_android.login;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.text.method.TransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.stars_project_android.HelloActivity;
import com.example.stars_project_android.R;
import com.example.stars_project_android.register.Register;
import com.example.stars_project_android.util.Constant;
import com.google.gson.Gson;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Date;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 密码登录界面
 */
public class PsdLogin extends AppCompatActivity implements View.OnClickListener {

    private TextView textRegister; //注册
    private EditText editPhone, editPsd;  //手机号， 验证码
    private Button btnLogin, btnCodeLogin;  //登录按钮，  密码登录按钮
    private ImageView eye;  //眼睛图标
    private boolean isHide = false;  //输入框密码是否是隐藏，默认为false
    private int code;   //返回的状态码
    private String msgCon;  //返回的错误信息

    //处理子线程的数据
    private Handler myHandler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //处理子线程发送的消息
            String result = (String) msg.obj;
            try {
                JSONObject jsonObject = new JSONObject(result);
                code = jsonObject.getInt("code");
                msgCon = jsonObject.getString("msg");
                Log.e("状态码",code+"");
                Log.e("返回的提示信息：",msgCon);
                if (code == 200){
                    JSONObject jsonObject1 = jsonObject.getJSONObject("date");
                    Constant.userId = jsonObject1.getString("userId");
                    Constant.starName = jsonObject1.getString("starName");
                    Constant.longitude = jsonObject1.getString("longitude");
                    Constant.latitude = jsonObject1.getString("latitude");
                    Constant.distance = jsonObject1.getInt("distance");
                    Constant.registerTime = jsonObject1.getString("registerTime");
                    Constant.psd = jsonObject1.getString("userPsdHx");
                    System.out.println("这是账号"+Constant.phone);
                    System.out.println("这是密码"+Constant.psd);
                    //在环信上登录用户
                    EMClient.getInstance().login(Constant.phone, Constant.psd, new EMCallBack() {
                        // 登录成功回调
                        @Override
                        public void onSuccess() {
                            //跳转到欢迎界面
                            Intent intent = new Intent(PsdLogin.this, HelloActivity.class);
                            startActivity(intent);
                        }

                        // 登录失败回调，包含错误信息
                        @Override
                        public void onError(int code, String error) {
                            System.out.println("登录失败啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊");
                        }

                    });
                } else {
                    //提示错误信息
                    Toast.makeText(PsdLogin.this,msgCon,Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_psd_login);
        //设置控件对象
        setView();
    }

    /**
     * 显示密码明文和密文
     */
    private void isShowPassword() {
        if(isHide == false) {
            //R.mipmap.password_show是表示显示密码的“眼睛”图标
            eye.setImageResource(R.mipmap.password_show);
            //密文
            HideReturnsTransformationMethod method1 = HideReturnsTransformationMethod.getInstance();
            editPsd.setTransformationMethod(method1);
            isHide = true;
        } else {
            //R.mipmap.password_miss是表示隐藏密码的“眼睛+斜杠”图标
            eye.setImageResource(R.mipmap.password_miss);
            //密文
            TransformationMethod method2 = PasswordTransformationMethod.getInstance();
            editPsd.setTransformationMethod(method2);
            isHide = false;
        }
        //重置光标位置
        int index = editPsd.getText().toString().length();
        editPsd.setSelection(index) ;
    }

    /**
     * 获取网络连接
     */
    private void getConn() {
        //向后端传递页面上获取的手机号和密码。
        //将数据封装
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("phoneNumber",editPhone.getText().toString());
            jsonObject.put("userPsd",editPsd.getText().toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Constant.phone = editPhone.getText().toString();
        Log.e("phone",editPhone.getText().toString());
        Log.e("password",editPsd.getText().toString());
        Log.e("json格式",jsonObject.toString());
        MediaType type = MediaType.parse("application/json;charset=utf-8");
        RequestBody requestBody = RequestBody.create(type,""+jsonObject.toString());

        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://192.168.1.7:8080/userInfo/login")
                .post(requestBody)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okhttp","请求失败");
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.e("okhttp","请求成功");
                //处理后端的数据
                response = okHttpClient.newCall(request).execute();
                String responseDate = response.body().string();
                Log.e("返回的数据",responseDate);
                //数据源发送改变，需要更新界面，使用Handler
                Message message = new Message();
                message.obj = responseDate;
                myHandler.sendMessage(message);//发送到主线程的消息队列
            }
        });
    }

    /**
     * 获取控件对象
     */
    private void setView() {
        textRegister = findViewById(R.id.text_register);
        textRegister.setOnClickListener(this);
        editPhone = findViewById(R.id.edit_phone);
        editPsd = findViewById(R.id.edit_psd);
        btnLogin = findViewById(R.id.btn_login);
        btnLogin.setOnClickListener(this);
        btnCodeLogin = findViewById(R.id.btn_codeLogin);
        btnCodeLogin.setOnClickListener(this);
        eye = findViewById(R.id.eye);
        eye.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.text_register:
                //点击注册跳转注册界面
                Intent intent = new Intent(this, Register.class);
                startActivity(intent);
                break;
            case R.id.eye:
                //点击眼睛显示密码
                isShowPassword();
                break;
            case R.id.btn_codeLogin:
                //点击验证码登录跳转到验证码登录界面
                Intent intent1 = new Intent(this,Login.class);
                finish();
                startActivity(intent1);
                break;
            case R.id.btn_login:
                //点击验证码登录跳转到验证码登录界面
                //获取后端连接，验证是否密码正确
                getConn();
                //正确跳转到欢迎界面并上传数据给数据库
//                Intent intent2 = new Intent(this,HelloActivity.class);
////                startActivity(intent2);
                break;
            default:
                break;
        }
    }
}